package notesDetection.wavPackage;

import java.io.File;
import java.io.IOException;

public class WavLoader
{
	private String _filename;
	private WavFile _wavFile;
	private boolean _isInitialized;
	private WavError _lastError;
	
	public enum WavError
	{
		WAV_OK,
		WAV_NOT_INITIALIZED,
		WAV_READ_FAILED
		
	}
	
	public WavLoader(String filename)
	{
		_filename = filename;
		_lastError = WavError.WAV_OK;
		_isInitialized = false;
	}
	
	public boolean InitializeWavFile()
	{
		try
		{
			_wavFile = WavFile.openWavFile(new File(_filename));
			_isInitialized = true;
		} catch (IOException e) {
			System.err.println(e.getMessage());
			_isInitialized = false;
		} catch (WavFileException e) {
			System.err.println(e.getMessage());
			_isInitialized = false;
		} // opening the file 
		return _isInitialized;
	}
	
	public int ReadFramesFromFile(double[][] outputBuffer, int numberOfFramesToRead)
	{
		if(!_isInitialized)
		{
			_lastError = WavError.WAV_NOT_INITIALIZED;
			return -1;
		}
		int framesRead;
		try
		{
			framesRead = _wavFile.readFrames(outputBuffer, numberOfFramesToRead);
			_lastError = WavError.WAV_OK;
		} catch (IOException e) {
			_lastError = WavError.WAV_READ_FAILED;
			e.printStackTrace();
			return -1;
		} catch (WavFileException e) {
			_lastError = WavError.WAV_READ_FAILED;
			e.printStackTrace();
			return -1;
		}
		
		return framesRead;
	}
	
	public WavError getLastError()
	{
		return _lastError;
	}
	
	public int getNumberOfChannels()
	{
		return _isInitialized ? _wavFile.getNumChannels() : -1;
	}
	
	public long getSampleFrequency()
	{
		return _wavFile.getSampleRate();
	}

	public long getNumberOfFrames() {
		return _wavFile.getNumFrames();
	}
	
}
